import os
import sys
import subprocess
import time

def print_header(message):
    """Print a formatted header message."""
    print("\n" + "=" * 80)
    print(f" {message}")
    print("=" * 80)

def run_command(command):
    """Run a command and print its output in real-time."""
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
        shell=True
    )
    
    for line in process.stdout:
        print(line, end='')
    
    process.wait()
    return process.returncode

def main():
    # Check if required packages are installed
    try:
        import qiskit
    except ImportError:
        print("Installing required packages...")
        run_command("pip install qiskit scikit-learn matplotlib pillow")
    print_header("Quantum Asteroid Detection Pipeline")
    
    # Step 1: Generate dataset
    print_header("Step 1: Generating dataset")
    run_command("python generate_images.py")
    
    # Step 2: Train quantum classifier
    print_header("Step 2: Training quantum classifier")
    run_command("python quantum_asteroid_detector.py")
    
    # Step 3: Test on a sample image
    print_header("Step 3: Testing on a sample image")
    
    # Find a sample image from the dataset
    sample_path = None
    if os.path.exists("dataset/with_asteroid"):
        files = os.listdir("dataset/with_asteroid")
        if files:
            sample_path = os.path.join("dataset/with_asteroid", files[0])
    
    if sample_path:
        print(f"Testing on sample image: {sample_path}")
        run_command(f"python detect_asteroid.py {sample_path}")
    else:
        print("No sample images found. Please run generate_images.py first.")
    
    print_header("Pipeline complete!")
    print("You can now use detect_asteroid.py to detect asteroids in your own images.")
    print("Usage: python detect_asteroid.py path/to/your/image.png")
    
    # Explain the quantum approach
    print("\nHow it works:")
    print("1. Images are processed and reduced to fit in a quantum system")
    print("2. A quantum circuit encodes image features using multiple rotation gates")
    print("3. Quantum superposition allows processing all feature combinations simultaneously")
    print("4. Quantum entanglement creates connections between qubits for enhanced processing")
    print("5. The quantum swap test algorithm measures similarity between quantum states")

if __name__ == "__main__":
    main()